package com.yuanhua.sim.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yuanhua.auth.common.constant.CacheKey;
import com.yuanhua.auth.server.utils.JwtTokenServerUtils;
import com.yuanhua.auth.utils.JwtUserInfo;
import com.yuanhua.auth.utils.Token;
import com.yuanhua.core.base.R;
import com.yuanhua.core.exception.code.ExceptionCode;
import com.yuanhua.sim.business.dto.LoginDTO;
import com.yuanhua.sim.business.dto.UserDTO;
import com.yuanhua.sim.business.entity.User;
import com.yuanhua.sim.business.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 认证管理器
 */
@Service
@Slf4j
public class AuthManager {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtTokenServerUtils jwtTokenServerUtils;

    //登录认证
    public R<LoginDTO> login(String account, String password) {
        //校验账号、密码是否正确
        R<User> userR = check(account, password);
        Boolean isError = userR.getIsError();
        if(isError){
            return R.fail("认证失败,用户名或密码不正确");
        }
        //为用户生成jwt令牌
        User user = userR.getData();
        Token token = generateUserToken(user);
        //封装返回结果
        LoginDTO loginDTO = LoginDTO.builder().
                            user(BeanUtil.copyProperties(userR.getData(), UserDTO.class)).
                            token(token).
                            build();
        return R.success(loginDTO);
    }

    //账号、密码校验
    public R<User> check(String account,String password){
        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getAccount, account));
        //将前端提交的密码进行md5加密
        String md5Hex = DigestUtils.md5Hex(password);
        if(user == null || !user.getPassword().equals(md5Hex)){
            //认证失败
            return R.fail(ExceptionCode.JWT_USER_INVALID);
        }
        //认证成功
        return R.success(user);
    }

    //为当前登录用户生成对应的jwt令牌
    public Token generateUserToken(User user){
        JwtUserInfo jwtUserInfo = new JwtUserInfo(user.getId(),user.getAccount(),user.getName());
        Token token = jwtTokenServerUtils.generateUserToken(jwtUserInfo, null);
        return token;
    }
}
